package com.learn.core.exception.handle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


/**
 * @author PC
 */
@RestControllerAdvice
public class ExceptionHandle {
    public final static Logger LOGGER = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<Object> handleAssertionError(HttpServletRequest request, HandlerMethod method, Exception ex) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn(String.format("%s/n%s", method.getShortLogMessage(), ex.getMessage()), ex);
        }
        // 构造返回的响应体
        Map<String, Object> responseBody = new HashMap<>();
        responseBody.put("timestamp", LocalDateTime.now());
        responseBody.put("error", "error.error");
        responseBody.put("message", ex.getMessage());
        responseBody.put("path", request.getRequestURI());

        return new ResponseEntity<>(responseBody, HttpStatus.OK);
    }

//    /**
//     * AccessDeniedException交由Security处理
//     */
//    @ExceptionHandler(value = AccessDeniedException.class)
//    @ConditionalOnClass(value = AccessDeniedException.class)
//    public void accessDeniedException(AccessDeniedException accessDeniedException) {
//        throw accessDeniedException;
//    }
}
